//
//  EQViewController.swift
//  DSP
//
//  Created by tucici on 2024/5/14.
//

import UIKit
import RealmSwift
import SwiftyJSON
import TCCKit
private enum CellType{
    case top(_ array:[ChannelModel])
    case swipe(_ array:[EQSwipeCellModule], _ ch:ChannelModel)
    case mid(_ module:EQSwipeCellModule, _ ch:ChannelModel , _ direction:EQMidCellDirection)
    case bottom(_ array:[GroupModel])
}
class EQViewController: DSBaseController {
    private var swipeCellModel : EQSwipeCellModule?
    private var array = [CellType]()
    private var effct_index = 100
    private var effct : Bool = false
    private lazy var groupArray2: [GroupModel] = {
        let array = [GroupModel(name: "EQ Defeat"),
                     GroupModel(name: "Audio Presets"),
                     GroupModel(name: "Reset EQ")]
        _ = array.map{$0.enable = true}
        return  array
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initUI()
    }
    
    override func initUI() {
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(CrossTopCell.self, forCellReuseIdentifier: CrossTopCell.ID())
        tableView.register(EQSwipeCell.self, forCellReuseIdentifier: EQSwipeCell.ID())
        tableView.register(EQMidCell.self, forCellReuseIdentifier: EQMidCell.ID())
        tableView.register(GroupCell.self, forCellReuseIdentifier: GroupCell.ID())
        tableView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.bottom.equalToSuperview().inset(KUITabBarHeight)
        }
    }
    
    @objc override func updateData() {
        super.updateData()
        if groupArray2.count <= 3 {
            groupArray2 = groupArray2 + groupArray
        }else{
            let group = groupArray2[0..<3]
            groupArray2 = group + groupArray
        }
        let array1 = [EQSwipeCellModule(name: "ONE", r: NSRange(location: 0, length: 8)),
                      EQSwipeCellModule(name: "TWO", r: NSRange(location: 8, length: 16)),
                      EQSwipeCellModule(name: "THREE", r: NSRange(location: 16, length: 24)),
                      EQSwipeCellModule(name: "FOUR", r: NSRange(location: 24, length: 31))]
        let siwpe = swipeCellModel ?? array1[0]
        array = [.top(APP.CHM.array),
                 .swipe(array1,APP.CHM.select_ch),
                 .mid(siwpe, APP.CHM.select_ch, .down("Freq")),
                 .mid(siwpe, APP.CHM.select_ch, .up("Q")),
                 .bottom(groupArray2)]
        tableView.reloadData()
    }
    
    override func sendData(){
        ///如果是选中effct，因为是全部通道都变成选择的数据，则要全部通道，全部信号都要发送一遍。
        let ch_array = effct ? APP.CHM.array : APP.CHM.array.filter({$0.select})
        if ch_array.isEmpty {return}
        ///到时候要优化
        for i in 0..<ch_array.count{
            let ch = ch_array[i]
            for j in 0..<ch.signArray.count{
                let sign = ch.signArray[j]
                _ = BLEData.EQ(ch_array, j, sign).write
            }
        }
    }
    
    ///同一group的通道的属性
    private func copyProperties(from ch:ChannelModel){
        guard let group = groupArray.first(where: {$0.contain(ch: ch)}) else {return}
        select_group_index = group.select ? group.num : 100
        if group.select == false || ch.select == false {return}
        for ch_t in group.chArr{
            if ch_t.num == ch.num {continue}
            let copiedSignArray = List<SignModule>()
            for sign in ch.signArray {
                copiedSignArray.append(sign.copy() as! SignModule)
            }
            ch_t.signArray = copiedSignArray
        }
    }
    
}

//MARK: - CrossTopCellDelegate
extension EQViewController : CrossTopCellDelegate{
    func select(ch: ChannelModel, index: IndexPath) {
        let group_select = groupArray.first(where: {$0.contain(ch: ch)  && $0.select}) ?? GroupModel()
        _ = APP.CHM.array.map{
            $0.select = (group_select.contain(ch: $0)) ? group_select.select : $0.num == ch.num
        }
        
        copyProperties(from: ch)
        select_ch_index = index.row
        updateData()
        sendData()
    }
}

//MARK: - EQSwipeCellDelegate
extension EQViewController : EQSwipeCellDelegate{
    func scrollTo(_ module: EQSwipeCellModule) {
        guard case let .mid(_, ch, direction1) = array[2] else {return}
        guard case let .mid(_, _, direction2) = array[3] else {return}
        array[2] = .mid(module, ch, direction1)
        array[3] = .mid(module, ch, direction2)
        swipeCellModel = module
        tableView.reloadData()
    }
    
    func swipe(_ sign:SignModule){
        select(sign)
    }
}


//MARK: - EQSwipeCellDelegate
extension EQViewController : EQMidCellDelegate{
    func select(_ sign:SignModule) {
        
        ///统一选中的通道的数据
        for ch in APP.CHM.array{
            if ch.select == false{ continue}
            for s in ch.signArray{
                s.select = s.name == sign.name
                if s.select == false {continue}
                s.frency = sign.frency
                s.gain = sign.gain
                s.quality = sign.quality
            }
        }
        select_ch_index = select_ch_index
        updateData()
        sendData()
    }
}

//MARK: - GroupCellDelegate
extension EQViewController : GroupCellDelegate{
    func select(_ group: GroupModel, _ index: Int) {
        switch group.name{
        case "EQ Defeat":
            group.select = !group.select
            _ = groupArray2.map{$0.enable = $0 == group ? $0.enable : !group.select}
            
            for ch in APP.CHM.array{
                ch.enable = !group.select
                for sign in ch.signArray{
                    sign.enable = !group.select
                }
            }
            tableView.reloadData()
            //sendData()
            return
        case "Audio Presets":
            let vc = EffectController()
            vc.select_index = effct_index
            let select_ch = select_ch_index
            present(vc, animated: false)
            let frency = [20, 25, 32, 40, 50, 63, 80, 100,
                          125, 160, 200, 250, 315, 400, 500, 630,
                          800, 1000, 1250, 1600, 2000, 2500, 3150, 4000,
                          5000, 6300, 8000, 10000,12500, 16000, 20000]
            vc.block = {[weak self] (data, index) in
                print("data =\(data) \n index=\(index)")
                self?.effct_index = index
                for ch in APP.CHM.array{
                    // 所有通道都要变成选中的preset
                    //if ch.select == false{continue}
                    for i in 0..<ch.signArray.count{
                        let sign  = ch.signArray[i]
                        sign.gain = Float(data[i])
                        sign.quality = 7.2
                        sign.frency = frency[i]
                    }
                }
                self?.select_ch_index = select_ch
                self?.effct = true
                self?.updateData()
                self?.sendData()
                self?.effct = false
            }
            return
        case "Reset EQ":
            CLHUD("Reset EQ Successfully",type: .info, callBack: nil)
            effct_index = 20
            for ch in APP.CHM.array{
                ch.initSignArr()
            }
            for ch in APP.CHM.array{
                _ = BLEData.resetEQ(ch).write
            }
        default:
            copyProperties(from: group.ch1)
            select_ch_index = group.select ? group.ch1.num - 1 : select_ch_index
        }
        updateData()
        sendData()
    }
}

//MARK: - UITableViewDataSource
extension EQViewController:UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return array.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        switch array[indexPath.row]{
        case let .top(array):
            let cell = tableView.dequeueReusableCell(withIdentifier: CrossTopCell.ID()) as! CrossTopCell
            cell.array = array
            cell.delegate = self
            return cell
        case let .swipe(array,ch):
            let cell = tableView.dequeueReusableCell(withIdentifier: EQSwipeCell.ID()) as! EQSwipeCell
            cell.array = array
            cell.model = ch
            cell.delegate = self
            return cell
        case let .mid(module, ch, direction):
            let cell = tableView.dequeueReusableCell(withIdentifier: EQMidCell.ID()) as! EQMidCell
            cell.direction = direction
            cell.module = module
            cell.ch = ch
            cell.delegate = self
            return cell
        case let .bottom(array):
            let cell = tableView.dequeueReusableCell(withIdentifier: GroupCell.ID()) as! GroupCell
            cell.array = array
            cell.delegate = self
            return cell
        }
    }
}
//MARK: - UITableViewDelegate
extension EQViewController:UITableViewDelegate{
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return chartView.bounds.height
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView()
        view.backgroundColor = .clear
        view.addSubview(chartView)
        chartView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        return view
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
}

